<template>
  <a-card :bordered="false">
    <!-- 查询区域 -->
    <div class="table-page-search-wrapper">
      <a-form layout="inline" @keyup.enter.native="searchQuery">
        <a-row :gutter="24">
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="所属区域">
              <j-select-depart placeholder="请选择有效区域id" v-model="queryParam.areaId" />
            </a-form-item>
          </a-col>

          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="点位类型">
              <j-dict-select-tag
                type="list"
                v-model="queryParam.temperatureData"
                dictCode="ps_point_type"
                placeholder="请选择点位类型"
              />
            </a-form-item>
          </a-col>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="点位名称">
              <a-input v-model="pointName" placeholder="请输入"></a-input>
            </a-form-item>
          </a-col>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="点位编号">
              <a-input v-model="queryParam.pointNo" placeholder="请输入"></a-input>
            </a-form-item>
          </a-col>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <span style="float: left; overflow: hidden" class="table-page-search-submitButtons">
              <a-button type="primary" @click="searchQuery" icon="search" style="margin: 0 auto 10px">查询</a-button>
              <a-button type="primary" @click="customerSearchReset" icon="reload" style="margin: 0 0 10px 8px"
                >重置</a-button
              >
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>
    <!-- 查询区域-END -->

    <!-- 操作按钮区域 -->
    <div class="table-operator">
      <a-button @click="showModal" type="primary" icon="plus">新增</a-button>
      <!--      <a-button type="primary" icon="download" @click="handleExportXls('点位表')">导出</a-button>-->
      <!--      <a-upload name="file" :showUploadList="false" :multiple="false" :headers="tokenHeader" :action="importExcelUrl" @change="handleImportExcel">-->
      <!--        <a-button type="primary" icon="import">导入</a-button>-->
      <!--      </a-upload>-->
      <!-- 高级查询区域 -->
      <!--      <j-super-query :fieldList="superFieldList" ref="superQueryModal" @handleSuperQuery="handleSuperQuery"></j-super-query>-->
      <a-dropdown v-if="selectedRowKeys.length > 0">
        <a-menu slot="overlay">
          <a-menu-item key="1" @click="batchDel"><a-icon type="delete" />删除</a-menu-item>
        </a-menu>
        <a-button style="margin-left: 8px"> 批量操作 <a-icon type="down" /></a-button>
      </a-dropdown>
    </div>

    <!-- table区域-begin -->
    <div>
      <div class="ant-alert ant-alert-info" style="margin-bottom: 16px">
        <i class="anticon anticon-info-circle ant-alert-icon"></i> 已选择
        <a style="font-weight: 600">{{ selectedRowKeys.length }}</a
        >项
        <a style="margin-left: 24px" @click="onClearSelected">清空</a>
      </div>

      <a-table
        ref="table"
        size="middle"
        :scroll="{ x: true }"
        bordered
        rowKey="id"
        :columns="columns"
        :dataSource="dataSource"
        :pagination="ipagination"
        :loading="loading"
        :rowSelection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
        class="j-table-force-nowrap"
        @change="handleTableChange"
      >
        <span slot="action" slot-scope="text, record">
          <a @click="editHandles(record)" class="ant-btn-group">编辑</a>
          <a-popconfirm title="确定删除吗?" @confirm="() => remove(record.id)">
            <a class="ant-btn-group">删除</a>
          </a-popconfirm>
        </span>
      </a-table>
    </div>

    <!--    <paishui-point-pos-modal ref="modalForm" @ok="modalFormOk"></paishui-point-pos-modal>-->
    <a-modal :title="title" v-model="visible" @ok="handleOk" @cancel="handleCancel" :width="800">
      <a-form-model :modal="newlyIncreased" class="form_add">
        <a-row type="flex" :gutter="16">
          <a-col :span="12">
            <a-form-model-item label="点位名称 " class="ant-form-item-required">
              <a-input v-model="newlyIncreased.pointName"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="点位编号">
              <a-input v-model="newlyIncreased.pointNo" :disabled="true"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="点位类型" class="form_temperatureData ant-form-item-required">
              <!--                <j-dict-select-tag placeholder="请选择点位类型" v-model="newlyIncreased.temperatureData" dictCode="ps_pip_type"/>-->
              <a-select v-model="newlyIncreased.temperatureData">
                <a-select-option :value="1">管点</a-select-option>
                <a-select-option :value="2">设备点</a-select-option>
                <a-select-option :value="3">建筑</a-select-option>
                <a-select-option :value="4">河流</a-select-option>
                <a-select-option :value="5">公路</a-select-option>
                <a-select-option :value="6">桥梁</a-select-option>
              </a-select>
            </a-form-model-item>
            <a-form-model-item label="管点类型" class="form_temperatureData ant-form-item-required"  v-if="newlyIncreased.temperatureData==1">
              <a-select v-model="newlyIncreased.pipType">
                <a-select-option :value="1">雨水井</a-select-option>
                <a-select-option :value="2">污水井</a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="所属区域" class="form_areaId ant-form-item-required" prop="areaId">
              <j-select-depart v-model="newlyIncreased.areaId" :multi="true" />
            </a-form-model-item>
          </a-col>
          <div style="margin-left: 10px">
            <div>
              <a-button @click="showMap = !showMap">{{ showMap ? '收起地图' : '展开地图' }}</a-button>
            </div>

            <div style="display: flex; padding: 0 8px; margin-top: 20px">
              <div>
                <div class="search">
                  <span style="margin-right: 5px; color: rgba(0, 0, 0, 0.85)">地址: </span>
                  <el-select
                    v-model="form.address"
                    filterable
                    remote
                    reserve-keyword
                    placeholder="请输入关键词"
                    :remote-method="remoteMethod"
                    :loading="loading"
                    :clearable="true"
                    size="mini"
                    @change="currentSelect"
                    style="width: 500px"
                  >
                    <el-option
                      v-for="item in options"
                      :key="item.name"
                      :label="item.name"
                      :value="item"
                      class="one-text"
                    >
                      <span style="float: left">{{ item.name }}</span>
                      <span style="float: right; color: #8492a6; font-size: 13px">{{ item.district }}</span>
                    </el-option>
                  </el-select>
                </div>
                <div id="container" class="container" v-show="showMap"></div>
              </div>
            </div>
          </div>
          <a-col :span="12" style="padding-left: 18px">
            <a-form-model-item label="经度">
              <a-input v-model="newlyIncreased.longitude"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="纬度" onblur="">
              <a-input v-model="newlyIncreased.latitude" @blur="handleMap"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="12" style="padding-left: 18px">
            <a-form-model-item label="备注">
              <a-input v-model="newlyIncreased.remark"></a-input>
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
    </a-modal>
  </a-card>
</template>

<script>
import '@/assets/less/TableExpand.less'
import { mixinDevice } from '@/utils/mixin'
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import PaishuiPointPosModal from '../modules/PaishuiPointPos/PaishuiPointPosModal'
import AMapLoader from '@amap/amap-jsapi-loader'
import { httpAction, getAction, delAction, postAction } from '@api/manage'
window._AMapSecurityConfig = {
  // 安全密钥
  securityJsCode: 'ecb9d215b9a5feeac1ea044eeb9198f4',
}
export default {
  name: 'PaishuiPointPosList',
  mixins: [JeecgListMixin, mixinDevice],
  components: {
    PaishuiPointPosModal,
  },
  data() {
    return {
      pointName: '',
      description: '点位表管理页面',
      title: '点位信息',
      inquire: {
        areaId: '',
        temperatureData: '',
        pointNo: '',
      },
      // 表头
      columns: [
        {
          title: '#',
          dataIndex: '',
          key: 'rowIndex',
          width: 60,
          align: 'center',
          customRender: (t, r, index) => {
            const { pageSize, current } = this.ipagination
            return (current - 1) * pageSize + parseInt(index) + 1
          },
        },
        {
          title: '点位名称',
          align: 'center',
          dataIndex: 'pointName',
        },
        {
          title: '点位编号',
          align: 'center',
          dataIndex: 'pointNo',
        },
        {
          title: '点位类型',
          align: 'center',
          dataIndex: 'temperatureData',
          customRender: (text, record, index) =>
            text
              ? text == 1
                ? '管点'
                : text == 2
                ? '设备点'
                : text == 3
                ? '建筑'
                : text == 4
                ? '河流'
                : text == 5
                ? '公路'
                : text == 6
                ? '桥梁'
                : '其他'
              : '--',
        },
        {
          title: '所属区域',
          align: 'center',
          dataIndex: 'areaId_dictText',
          customRender: this.changeRowSpan,
        },
        {
          title: '位置',
          align: 'center',
          dataIndex: 'position',
          customRender: (text, record, index) => (text == null ? '--' : text),
        },
        {
          title: '经度',
          align: 'center',
          dataIndex: 'longitude',
        },
        {
          title: '纬度',
          align: 'center',
          dataIndex: 'latitude',
        },
        {
          title: '备注',
          align: 'center',
          dataIndex: 'remark',
        },
        {
          title: '操作',
          dataIndex: 'action',
          align: 'center',
          fixed: 'right',
          width: 147,
          scopedSlots: { customRender: 'action' },
        },
      ],
      url: {
        list: '/paishui/paishuiPointPos/list',
        add: '/paishui/paishuiPointPos/add',
        delete: '/paishui/paishuiPointPos/del',
        deleteBatch: '/paishui/paishuiPointPos/deleteBatch',
        exportXlsUrl: '/paishui/paishuiPointPos/exportXls',
        importExcelUrl: 'paishui/paishuiPointPos/importExcel',
        areaList: '/paishui/area/list',
        edit: '/paishui/paishuiPointPos/edit',
      },
      dictOptions: {},
      superFieldList: [],
      visible: false,
      newlyIncreased: {
        pointName: '',
        pointNo: '',
        temperatureData: undefined,
        status: undefined,
        longitude: '',
        latitude: '',
        remark: '',
        areaId: '',
        position: '',
        pipType:undefined
      },
      validatorRules: {
        pointName: [{ required: true, message: 'Please input Activity name' }],
      },
      handleRedact: false,
      //地图实例
      map: null,
      //标记点
      marker: '',
      // 地址逆解析
      geoCoder: null,
      // 搜索提示
      AutoComplete: null,
      // 搜索关键字
      keywords: '',
      // 位置信息
      form: {
        lng: '',
        lat: '',
        address: '',
        //地区编码
        adcode: '',
      },
      // 搜索节流阀
      loading: false,
      // 搜索提示信息
      options: [],
      labelCol: { span: 4 },
      wrapperCol: { span: 14 },
      locationName: {},
      dataInitializeIpagination: {
        pageIndex: 1,
        pageSize: 10,
        total: 0,
        showTotal: (total, range) => range[0] + '-' + range[1] + ' 共' + total + '条',
      },
      showMap: true,
    }
  },
  watch: {
    pointName(pointName) {
      if (pointName) {
        this.queryParam.pointName = `*${pointName}*`
      } else {
        this.queryParam.pointName = ''
      }
    },
  },
  created() {
    this.getSuperFieldList()
  },
  computed: {
    importExcelUrl: function () {
      return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`
    },
  },
  methods: {
    customerSearchReset() {
      this.pointName = ''
      this.searchReset()
    },
    initDictConfig() {},
    getSuperFieldList() {},
    showModal() {
      this.visible = true
      this.initMap()
    },
    handleOk(e) {
      if (this.handleRedact) {
        console.log(this.handleRedact)
        this.newlyIncreased.position = this.form.address
        postAction(this.url.edit, this.newlyIncreased).then((res) => {
          this.newlyIncreased = {}
          this.visible = false
          this.searchQuery()
          this.handleRedact = false
        })
      } else {
        //地址回显
        this.newlyIncreased.position = this.form.address
        if (this.newlyIncreased.pointName === '') {
          this.$message.error('点位名称不能为空')
        } else if (this.newlyIncreased.temperatureData === undefined) {
          this.$message.error('点位类型不能为空')
        } else if (this.newlyIncreased.pipType === undefined&&this.newlyIncreased.temperatureData ==1) {
          this.$message.error('管点类型不能为空')
        }else if (this.newlyIncreased.areaId === '') {
          this.$message.error('区域不能为空')
        } else {
          httpAction(this.url.add, this.newlyIncreased, 'post').then((res) => {
            console.log('res===', res)
            if (res.code !== 200) {
              this.$message.error(`${res.message}`)
              return
            } else {
              this.newlyIncreased = {}
              this.visible = false
              this.form.address = ''
              this.searchQuery()
            }
          })
        }
      }
    },
    handleCancel() {
      // this.$refs.ruleForm.resetFields();
      this.newlyIncreased = {}
    },
    /*
     * 初始化地图组件
     * */
    initMap() {
      AMapLoader.load({
        // 你申请的Key
        key: '7bf1afe0a111e75bc96b5f5d0553b5f3',
        version: '2.0',
        // 需要用到的插件
        plugins: ['AMap.Geocoder', 'AMap.AutoComplete'],
      })
        .then((AMap) => {
          this.map = new AMap.Map('container', {
            viewMode: '3D', //是否为3D地图模式
            zoom: 7, //初始化地图级别
            center: [119.46160138147026, 28.938609191923716], //初始化地图中心点位置
          })
          //地址逆解析插件
          this.geoCoder = new AMap.Geocoder({
            city: '010', //城市设为北京，默认：“全国”
            radius: 1000, //范围，默认：500
          })
          // 搜索提示插件
          this.AutoComplete = new AMap.AutoComplete({ city: '全国' })
          //点击获取经纬度;
          this.map.on('click', (e) => {
            let { lng, lat } = e.lnglat
            console.log('lng', lng)
            lng = ('' + lng).length > 12 ? lng.toFixed(8) : lng
            lat = ('' + lat).length > 11 ? lat.toFixed(8) : lat
            this.newlyIncreased.longitude = lng
            this.newlyIncreased.latitude = lat
            // 获取经纬度
            this.form.lng = lng
            this.form.lat = lat
            // 清除点
            this.removeMarker()
            // 标记点
            this.setMapMarker()
          })
        })
        .catch((err) => {
          // 错误
          console.log(err)
        })
    },
    // 标记点
    setMapMarker() {
      // 自动适应显示想显示的范围区域
      // this.map.setFitView();
      this.marker = new AMap.Marker({
        map: this.map,
        position: [this.newlyIncreased.longitude, this.newlyIncreased.latitude],
      })
      // 逆解析地址
      this.toGeoCoder()
      // this.map.setFitView();
      this.map.add(this.marker)
    },
    // 清除点
    removeMarker() {
      if (this.marker) {
        this.map.remove(this.marker)
      }
    },
    // 逆解析地址
    toGeoCoder() {
      console.log('逆解析地址')
      let lnglat = [this.newlyIncreased.longitude, this.newlyIncreased.latitude]
      console.log('lnglat', lnglat)
      this.geoCoder.getAddress(lnglat, (status, result) => {
        if (status === 'complete' && result.regeocode) {
          this.form.address = result.regeocode.formattedAddress
          this.removeMarker()
          this.marker = new AMap.Marker({
            map: this.map,
            position: [this.newlyIncreased.longitude, this.newlyIncreased.latitude],
          })
          this.map.add(this.marker)
        } else {
          this.$message.error('获取地址失败，请检查经纬度是否正确。')
        }
      })
    },
    // 搜索
    remoteMethod(query) {
      // console.log(query);
      if (query !== '') {
        this.loading = true
        setTimeout(() => {
          this.loading = false
          this.AutoComplete.search(query, (status, result) => {
            console.log('result/////////', result)
            this.options = result.tips
          })
        }, 200)
      } else {
        this.options = []
      }
    },
    // 选中提示
    currentSelect(val) {
      // 清空时不执行后面代码
      if (!val) {
        return
      }
      console.log('选中提示', val)
      let { lng, lat } = val.location
      lng = ('' + lng).length > 12 ? lng.toFixed(8) : lng
      lat = ('' + lat).length > 11 ? lat.toFixed(8) : lat
      this.form = {
        lng,
        lat,
        address: val.district + val.address,
        adcode: val.adcode,
      }
      this.newlyIncreased.longitude = lng
      this.newlyIncreased.latitude = lat
      this.newlyIncreased.position = val.district + val.addressqq
      this.locationName.name = val.district
      this.removeMarker()
      // 标记点
      this.setMapMarker()
    },
    /*
     * 逻辑删除 通过Id
     * */
    remove(id) {
      // console.log('removeId',id)
      // let params = this.getQueryParams();//查询条件
      let that = this
      delAction(that.url.delete, id).then((res) => {
        that.$message.success('删除成功！')
        this.searchQuery()
      })
    },
    /*
     * 编辑
     * */
    editHandles(record) {
      console.log('record', record)
      this.visible = true
      this.newlyIncreased = record
      this.form.address = record.position
      this.handleRedact = true
    },
    /*
     * 复杂数据渲染函数
     * */
    changeRowSpan(value, row, index) {
      if (!value) return '--'
      let val
      // console.log(value)

      let arr = value ? value.split('/') : value
      // console.log(arr)
      if (arr.length == 2) {
        // console.log(arr)
        arr = arr.slice(1)
        arr[0] += '省'
        val = arr.join('')
        // console.log(arr)
      } else if (arr.length == 1) {
        val = arr.join('')
      } else {
        arr = arr.slice(2)
        arr[0] += '市'
        val = arr.join('')
        // console.log(arr)
      }
      return val
    },
    // 查询
    onSubmit() {
      this.queryParam.areaId = this.inquire.areaId
      this.queryParam.temperatureData = this.inquire.temperatureData
      this.queryParam.pointNo = this.inquire.pointNo
      this.searchQuery()
    },
    //重置
    empty() {
      this.queryParam.areaId = ''
      this.queryParam.temperatureData = ''
      this.queryParam.pointNo = ''
      this.searchQuery()
    },
    handleMap() {
      this.toGeoCoder()
    },
  },
}
</script>
<style scoped>
@import '~@assets/less/common.less';
#container {
  width: 490px;
  height: 242px;
  border: #c0c4cc solid 1px;
  border-radius: 5px;
}
.ant-btn-group {
  margin-right: 5px;
}
.ant-row-flex >>> .ant-col-6 {
  width: 10%;
}
.ant-row >>> .ant-col-4 {
  width: 36.666667%;
}
.search {
  margin-bottom: 25px;
}
.form_add >>> .ant-form-item {
  display: flex;
}
.form_temperatureData >>> .ant-form-item-control-wrapper,
.form_areaId >>> .ant-form-item-control-wrapper {
  width: 186px;
}
.ant-form-item-required >>> label:before {
  display: inline-block;
  margin-right: 4px;
  color: #f5222d;
  font-size: 14px;
  font-family: SimSun, sans-serif;
  line-height: 1;
  content: '*';
}
</style>
